import { Injectable, ForbiddenException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserFavoriteEntity } from './entities/user-favorite.entity';
import { PostEntity } from 'src/post/entities/post.entity';

@Injectable()
export class UserFavoriteService {
  constructor(
    @InjectRepository(UserFavoriteEntity)
    private favRepo: Repository<UserFavoriteEntity>,
    @InjectRepository(PostEntity)
    private postRepo: Repository<PostEntity>,
  ) {}

  async favorite(postId: number, userId: number) {
    const exist = await this.favRepo.findOne({
      where: {
        post: { id: postId },
        user: { id: userId },
      },
    });
    if (exist) throw new ForbiddenException('你已经收藏过了');

    await this.favRepo.save({
      post: { id: postId },
      user: { id: userId },
    });

    await this.postRepo.increment({ id: postId }, 'favoriteCount', 1);
    return { message: '收藏成功' };
  }

  async getFavorites(userId: number) {
    const favorites = await this.favRepo.find({
      where: { user: { id: userId } },
      relations: ['post'],
    });
    return favorites.map(fav => fav.post);
  }
}
